package cn.relx.org.service.impl;

import cn.relx.basic.config.BussinessException;
import cn.relx.basic.util.BaiduAuditUtils;
import cn.relx.org.domain.Employee;
import cn.relx.org.domain.Shop;
import cn.relx.org.mapper.EmployeeMapper;
import cn.relx.org.mapper.ShopMapper;
import cn.relx.org.service.IShopService;
import cn.relx.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author relx
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        Employee employee = this.verify(shop, admin);
        // 存入数据了
        // 添加shop表
        shopMapper.add(shop);
        if(null == employee){
            //添加emp
            employee = admin;
            employeeMapper.add(employee);
        }
        employee.setShopId(shop.getId());
        employeeMapper.update(employee);
        Shop uptShop = new Shop();
        uptShop.setId(shop.getId());
        uptShop.setAdminId(employee.getId());
        shopMapper.update(uptShop);
    }

    private Employee verify(Shop shop, Employee admin) {
        //检验参数
        if(StringUtils.isBlank(shop.getName())){
            throw new BussinessException("店铺名不能为空!");
        }
        //检验两次密码是否一致
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BussinessException("两次密码不一致!");
        }
        //AI检验
        if(BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BussinessException("店铺LoGo不合规!");
        }
        if(BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BussinessException("店铺名称不合规!");
        }
        //店铺名称是否存在
        Shop tmpShop = shopMapper.findByName(shop.getName());
        if (null != tmpShop){
            throw new BussinessException("店铺名称已存在!");
        }
        // 当前管理员是否管理了其他店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if(null != employee && null != employee.getShopId()){
            Shop shopById = shopMapper.findById(employee.getShopId());
                if(shopById.getAdminId().equals(employee.getId())){
                    throw new BussinessException("管理员已关联店铺!");
                }
        }
        return employee;
    }
}
